/**
 * 小程序提示工具Hook
 * @param options 配置项
 *   - style: 自定义样式
 *   - duration: 默认显示时长
 */
export const useWarns = (options?: {
  style?: string
  duration?: number
}): {
  loading: (title?: string, mask?: boolean) => void
  hideLoading: () => void
  toast: (title: string, icon?: 'success' | 'error' | 'loading' | 'none') => void
  success: (title: string) => void
  error: (title: string) => void
  alert: (title: string, content?: string) => Promise<boolean>
  confirm: (title: string, content?: string) => Promise<boolean>
  actionSheet: (itemList: string[], title?: string) => Promise<number | null>
} => {
  const defaultOptions = {
    duration: 2000,
    ...options
  }

  return {
    /**
     * 显示加载提示
     * @param title 提示文字
     * @param mask 是否显示透明蒙层
     */
    loading: (title = '加载中...', mask = true) => {
      wx.showLoading({
        title,
        mask
      })
    },

    /**
     * 隐藏加载提示
     */
    hideLoading: () => {
      wx.hideLoading()
    },

    /**
     * 显示Toast提示
     * @param title 提示文字
     * @param icon 图标类型
     */
    toast: (title: string, icon: 'success' | 'error' | 'loading' | 'none' = 'none') => {
      wx.showToast({
        title,
        icon,
        duration: defaultOptions.duration,
        mask: true
      })
    },

    /**
     * 显示成功提示
     * @param title 提示文字
     */
    success: (title: string) => {
      wx.showToast({
        title,
        icon: 'success',
        duration: defaultOptions.duration,
        mask: true
      })
    },

    /**
     * 显示错误提示
     * @param title 提示文字
     */
    error: (title: string) => {
      wx.showToast({
        title,
        icon: 'error',
        duration: defaultOptions.duration,
        mask: true
      })
    },

    /**
     * 显示警告弹窗(只有一个确定按钮)
     * @param title 标题
     * @param content 内容
     * @returns Promise<boolean> 总是返回true
     */
    alert: (title: string, content = '') => {
      return new Promise(resolve => {
        wx.showModal({
          title,
          content,
          showCancel: false,
          success: () => resolve(true)
        })
      })
    },

    /**
     * 显示确认弹窗(有确定和取消按钮)
     * @param title 标题
     * @param content 内容
     * @returns Promise<boolean> 用户点击确定返回true，取消返回false
     */
    confirm: (title: string, content = '') => {
      return new Promise(resolve => {
        wx.showModal({
          title,
          content,
          success: res => resolve(res.confirm)
        })
      })
    },

    /**
     * 显示操作菜单
     * @param itemList 按钮文字数组
     * @param title 标题
     * @returns Promise<number | null> 返回点击的按钮索引(从0开始)，取消返回null
     */
    actionSheet: (itemList: string[], title = '') => {
      return new Promise(resolve => {
        wx.showActionSheet({
          itemList,
          title,
          success: res => resolve(res.tapIndex),
          fail: () => resolve(null)
        })
      })
    }
  }
}
